/*
 * Copyright (c) 2017. Tencent BlueKing
 */

package com.tencent.bk.core.sdk.protocol;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.tencent.bk.utils.json.JsonUtil;
import com.tencent.bk.utils.json.annotation.SkipLogField;
import lombok.Getter;
import lombok.Setter;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;

/**
 * ESB请求基础协议，后续其他接口根据此继承在子类中增加对应的参数
 */
@Setter
@Getter
public class ESBReq {

    @JsonProperty("app_code")
    private String appCode;

    @SkipLogField("app_secret")
    @JsonProperty("app_secret")
    private String appSecret;

    @JsonProperty("username")
    private String userName;
    @JsonProperty("bk_token")
    private String bkToken;

    /**
     * 不打印出SkipLogFields指定的字段 避免日志泄露出敏感信息
     */
    @Override
    public String toString() {
        return JsonUtil.skipLogFields(this);
    }

    /**
     * 生成urlParams
     */
    public String toUrlParams() {
        StringBuilder urlString = new StringBuilder(512);
        char c = '?';
        Class<?> aClass = getClass();
        while (aClass != null) {
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field field : declaredFields) {

                String key;
                JsonProperty annotation = field.getAnnotation(JsonProperty.class);
                if (annotation != null) {
                    key = annotation.value();
                } else {
                    key = field.getName();
                }
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                    try {
                        Object b = field.get(this);
                        if (b != null) {
                            urlString.append(c).append(key).append('=').append(urlEncode(b.toString()));
                        }
                    } catch (IllegalAccessException ignored) {
                    } finally {
                        field.setAccessible(false);
                    }
                }
                if (c == '?') {
                    c = '&';
                }
            }
            aClass = aClass.getSuperclass();
        }
        return urlString.toString();
    }


    /**
     * 进行URL编码
     */
    private String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("encode failed");
        }
    }
}
